from PIL import Image
from time import sleep
from multiprocessing import Pool
import os
import re
import sys
import signal
import time

def signal_handler(signal, frame):

    os.system("adb shell rm /sdcard/screenshot.png >nul 2>&1")

    sys.exit(0)


def scap(howmany = 0):

    os.system("adb devices")
    
    i=1
    for f in os.listdir():
        if ( f[:2]=='l.' and f[-4:]=='.png' and f[-8:-4] != 'temp'):
            while i==int(f[-8:-4]):
                i=i+1

    times=1
    if howmany<=0 : return

    while True:

        # os.system("adb exec-out screencap -p > l.temp.0.png") ; open('l.temp.png', 'wb').write(open('l.temp.0.png', 'rb').read().replace(b'\r\n',b'\n')) # over Android 6
        os.system("adb shell screencap -p /sdcard/screenshot.png && adb pull /sdcard/screenshot.png l.temp.png") # under Android 6
        
        # thistime = str(time.strftime("%d_%H-%M-%S", time.localtime()))
        # thistime = str(time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime()))

        Image.open('l.temp.png').crop((50,250,670,1200)).save('l.%s.png' %'{:04}'.format(i) ,'PNG') # Sumsang
        # Image.open('l.temp.png').crop((0,150,720,1440)).save('l.%s.png' %'{:04}'.format(i),'PNG') # Redmi 6a
        # Image.open('l.temp.png').crop((50,300,670,1200)).save('l.%s.png' %'{:04}'.format(i),'PNG') # Redmi 4x

        if os.path.exists('l.%s.png' %'{:04}'.format(i-1)) :
            if os.path.getsize('l.%s.png' %'{:04}'.format(i-1)) == os.path.getsize('l.%s.png' %'{:04}'.format(i)) :
                i=i-1
                if  howmany<=times :
                    os.remove('l.%s.png' %'{:04}'.format(i+1))

        print(" Screencap> %s (%s)/ %s" %(times, i, howmany), end='\r\r')
        
        i = i+1
        times = times+1
        if howmany<times : break
    
    os.remove('l.temp.png')
    os.system("adb shell rm /sdcard/screenshot.png >nul 2>&1")



def ocrmp(f):

    if ( f[:2]=='l.' and f[-4:]=='.png' and f[-8:-4] != 'temp' and f[2:6]!='done' and f!='l.txt'):
        i = int(f[-8:-4])

        print(" Ocr> (%s)" %i)
        os.system("tesseract l.%s.png l.%s --dpi 300 -l chi_sim >nul 2>&1" %('{:04}'.format(i), '{:04}'.format(i)))

        os.rename('l.%s.png' %'{:04}'.format(i), 'l.done.%s.png' %'{:04}'.format(i))


def ocr():

    print('\n')

    Pool().map(ocrmp, os.listdir())

    for f in os.listdir() :
        if ( f[:2]=='l.' and f[-4:]=='.txt' and f[-8:-4] != 'temp' and f[2:6]!='done' and f!='l.txt'):
            i = int(f[-8:-4])
            open('l.txt', mode='a', encoding='UTF8').writelines('## %s\n\n' %'{:04}'.format(i))
            for line in open('l.%s.txt' %'{:04}'.format(i), mode='r', encoding='UTF8'):
                open('l.txt', mode='a', encoding='UTF8').writelines(line)

            open('l.txt', mode='a', encoding='UTF8').write('\n\n\n')
            os.remove('l.%s.txt' %'{:04}'.format(i))


def main(argv):

    signal.signal(signal.SIGINT, signal_handler)

    if argv!=[]:
        try: scap(int(argv[0]))
        except:
            print(" !! There may be a problem with the ADB command")
            sys.exit(0)
    ocr()


if __name__ == "__main__":
    main(sys.argv[1:])
